const http = require("http")
//项目根目录
global.$PATH = process.cwd();
//配置文件
global.gem_config = require(process.cwd()+"/gem.config");
//模块加载器
global.loader = require(process.cwd()+gem_config.global_module['loader'])
//初始化模块
global.init=[];


//服务启动器
module.exports={
    //启动项目
    start(){
        //初始化一些模块后启动服务
        this.init().then(e=>{
            //=====================启动服务
            let server = http.createServer(loader("inlet"));
            server.listen(gem_config.dev.port++,gem_config.dev.host,ts);
            server.on("error",()=>{
                console.log((global.config.dev.port-1)+"端口被占用,更改端口");
                server.listen(global.config.dev.port++,global.config.dev.host,ts);
            });
        });
    },
    //添加项目需要使用到的模块
    use(...data){
        let name,fun,bool=false;
        if(data.length===1){
            fun =loader(name);
        }else if(data.length===2){
            if(typeof data[1] === 'boolean'){
                bool = data[1];
                fun = loader(data[0]);
                name = data[0];
            }else{
                name = data[0];
                if(typeof data[1]==='string'){
                    fun = loader(data[1])
                }else{
                    fun = data[1];
                }
            }
        }else if(data.length===3){
            name=data[0];
            typeof data[1]==='string'?(fun=loader(data[1])):(fun=data[1]);
            bool = data[2];
        }

        global[name]=fun;
        if(bool)global.init.push(fun);
    },
    //初始化模块
    async init(){
        await Promise.all(global.init.map(async e=>{
            if(typeof e === 'function' && !e.start){
                await e();
            }else if(typeof e === 'object'){
                if(e.start){
                   await e.start();
                }
            }
        }))

        //调试使用
        console.logid=function(data){
            console.log("调用者",async_hooks.triggerAsyncId(),'本身>>', async_hooks.executionAsyncId(),data);
        }

        //不同的输出颜色
        console.red = (...data)=>{console.log('\x1B[31m',...data);}
        console.green=(...data)=>{console.log('\x1B[32m',...data);}
        console.yellow =(...data)=>{console.log('\x1B[33m',...data)}

        //提示语句
        console.resend=(req,time)=>{
            if(req._url==="/favicon.ico")return
            !time && (time=global.time())
            let sj = ((global.time()-time)/1000).toFixed(3);
            let str = global.date('Y-d-m H:i:s ')+req.statusCode+" "+sj+"ms"+" "+req.method+" "+req._url;
            req.statusCode!==404?console.green(str):console.red(str)
            console.log();
        }
    }
}
//提示
function ts(){
    if(this.status === undefined){
        //置顶一下
        global.clear();
        this.status=true;
        status=false;
        let IP = loader('fun').local_ip();
        console.log("GEM框架运行成功,请使用下面的网址访问网站");
        for(let a of IP){
            console.log(`Server running at http://${a.address}:`+(gem_config.dev.port-1)+'/');
        }
        // console.log("外网访问：")
        // for(let a of IP){
        //     if(a.address==="127.0.0.1")return
        //     console.log(`Server running at http://${a.address}:`+(gem_config.dev.port-1)+'/');
        // }
    }
}
